package main

import (
	"go.uber.org/zap"
	"sheep_script/core"
	"sheep_script/global"
	"sheep_script/initialize"
	"sheep_script/model"
	"sheep_script/model/sponsor"
	"time"
)

func init() {
	initialize.InitConfig()
	global.Logger = core.InitLogger()
	initialize.InitDB()
}

func main() {
	for {
		updateSponsorStatus()
		time.Sleep(12 * time.Hour)
	}
}

func updateSponsorStatus() {
	// 查询数据
	var userSponsor []sponsor.UserSponsor
	err := global.Mysql.Model(sponsor.UserSponsor{}).
		Where("status = ?", sponsor.UserSponsorStatusDefault).
		Where("deleted", model.DeletedNo).
		Find(&userSponsor).Error
	if err != nil {
		global.Logger.Error("userSponsor-err:", zap.Error(err))
		return
	}

	now := time.Now().Unix()
	for _, item := range userSponsor {
		coverTimestamp := now - int64(item.Cycle*7*24*60*60)
		coverTime := time.Unix(coverTimestamp, 0)
		// 已出栏
		if item.StartTime.Before(coverTime) {
			err = global.Mysql.Model(sponsor.UserSponsor{}).
				Where("id = ?", item.ID).
				Where("status = ?", sponsor.UserSponsorStatusDefault).
				Update("status", sponsor.UserSponsorStatusEnd).Error
			if err != nil {
				global.Logger.Error("userSponsor-update-err:", zap.Error(err))
			}
		}
	}
}
